package de.dhbw.karlsruhe.picsim.gui.editor;

import de.dhbw.karlsruhe.picsim.model.memory.RegisterValue;
import de.dhbw.karlsruhe.picsim.model.memory.impl.RegisterValueImpl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import javax.swing.table.TableCellEditor;
import java.awt.*;

/**
 * Created by IntelliJ IDEA.
 * User: user
 * Date: May 6, 2010
 * Time: 1:08:46 AM
 */
public final class HexEditor extends AbstractCellEditor implements TableCellEditor {
    private static final Log log = LogFactory.getLog(HexEditor.class);
    private final JTextField jTextField;

    public HexEditor() {
        jTextField = new JTextField();
    }


    @Override
    public Component getTableCellEditorComponent(final JTable table, final Object value, final boolean isSelected,
                                                 final int row, final int column) {
        jTextField.setText(Integer.toHexString(((RegisterValue) value).asInteger()));
        return jTextField;
    }

    @Nullable
    @Override
    public Object getCellEditorValue() {
        final String s = jTextField.getText();
        try {
            final int i = s.isEmpty() ? 0 : Integer.parseInt(s, 16);
            return RegisterValueImpl.createSafe(i);

        } catch (NumberFormatException e) {
            log.info("Illegal user input leads to", e);
            return null;
        }
    }
}
